<template>
      <el-tree
          ref="tree"
          :data="data"
          :default-expand-all=true
          :props="{
                children: 'children',
                label: 'title',
                key:'id'
              }"
          :indent='10'
          :highlight-current=true
          @node-click="handleClick"
      >
        <template #default="{ node }">
          <div class="node-show">
             <span :class="['custom-node', computedResulte(node)]" >
              {{ node.label }}
                <el-icon style="position: absolute; right: 0;bottom: 2px; width: 20%; height: 100%; color: gray"
                             >
                    <RemoveFilled  v-if="shouldDisplayIcon(node,'remove')" style="width: 400px; height: 100%;"  @click="handleRemove($event,node)"/>
                     <CirclePlusFilled  v-if="shouldDisplayIcon(node,'plus')" style="width: 400px; height: 100%;" @click="handlePlusClick($event,node)" />
                </el-icon>
              </span>
          </div>
        </template>
      </el-tree>

</template>

<script setup lang="ts">
import {RemoveFilled} from "@element-plus/icons-vue";
import {CirclePlusFilled} from "@element-plus/icons-vue";
import {nextTick, type PropType, ref,defineEmits} from "vue";
import {ElMessage} from "element-plus";
import type {DetailModeSideBarForm} from "@/api/types/detailmodel/detailModeSideBar";
import {createDetailModeSideBarApi} from "@/api/modules/detailModel/detailModeSideBar";


// 1. 定义可定制的Props（父组件传递）
const props = defineProps({
  indexList: {
    type: Array as PropType<{ id: string, title: string }[]>,  // 使用 PropType 来指定数组中每个元素的类型
    default: () => []
  },
  noShowPlus: {
    type: Array as PropType<string[]>,
    required: false, // 如果这个prop是可选的
    default: () => [] // 如果没有传递值，默认是空数组
  },
  masterId: Number
});

let data = ref(props.indexList);  // 组件内部维护输入值，避免频繁触发父组件更新

let tree = ref();  // 组件内部维护输入值，避免频繁触发父组件更新

/**
 * 子调父 定义方法由父组件实现
 */
const emit = defineEmits(['scroll-to-section', 'add-title','remove-title']);


/**
 * 这里不用能computer，因为返回的是一个getter方法而不是字符串
 */
let computedResulte = (node: any) => {
  return `level-${node.level}`;
}

let resetChildTree = (children: any) => {
  console.log('收到父组件的整可数',children);
  nextTick(() => {
    tree.value.expandAll();  // 展开所有节点
  });
}

let getChildNumber = (level : number) => {
  return returnChildNumber(level, tree.value.root.childNodes);
}

let getAllTree = () => {
  return tree.value.root;
}

/**
 * 获取对应层级的总个数
 * 递归：一个金字塔，由终点条件作为的底部，然后从的金字塔底部开始一层层的往上算，得到出口
 * 树状直接用封装好的childNodes比较好
 */
let returnChildNumber = (level: number, trees : any, nodeLen = 0, nodes = <any>[]) => {

  if (!trees || trees.length === 0) {
    return 0;
  }

  //终止条件 有儿子们 且 层次小于4
  trees.forEach((node: any) => {
    if (node.level > 4){
       return
    }

    if (node.level === level) {
      nodes.push(node)
      nodeLen++; //算当前
    }
    nodeLen += returnChildNumber(level,node.childNodes,0,nodes);//逐个算下一层
  })
  //累加执行
  return nodeLen;
}

//輸入2 出 4
//輸入3 出 //第一层0  第二层 1,1,3  第三层0


let addRootTitle= (type : string,newNode :any) => {
  if (type === 'one'){
    // let node = tree.value.getNode("ncPassing");
    let node = tree.value.data.find((i: any) => i.id === 'detail-content');
    if (!node?.children) {
      node.children = []
    }
    //let newNode2 = Object.assign({}, node);  赋值用
    // JSON.parse(JSON.stringify(node));  深拷贝
    newNode.title = '标题'+node.children.length;
    //需要存顺序
    let create :DetailModeSideBarForm = {
      id: newNode.id,
      label:newNode.title,
      ext1: props.masterId,
      ext: getChildNumber(2),
      ext2: 1,
    }
    createDetailModeSideBarApi(create).then(res => {
      ElMessage.success('保存成功')
    })

    node.children.push(newNode)
  }

  if (type === 'two'){
    //找到二级最后一个节点
    let node = tree.value.data.find((i: any) => i.id === 'detail-content');
    console.log('ncPassingsssss',node);
    //没有就直接不操作
    if (!node?.children || node?.children.length === 0) {
      return
    }
    //获取最后一个
    let lastNode = node.children[node.children.length-1]
    newNode.title = '副标题'+lastNode.children.length;
    //需要存顺序
    let create :DetailModeSideBarForm = {
      id: newNode.id,
      parentId:lastNode.id,
      label:newNode.title,
      ext1: props.masterId,
      ext: getChildNumber(3),
      ext2: 2,
    }
    createDetailModeSideBarApi(create).then(res => {
      ElMessage.success('保存成功')
    })


    lastNode.children.push(newNode)
    return true;
  }
  return false;
}

let initTree = (tress : any) =>{
  data.value = tress
}

let shouldDisplayIcon = (node :any,type : string) => {

  if(node.level === 4 && type ==='plus') {
    return false;
  }

  if (node && node.data && node.data.id !== undefined) {
    return !props.noShowPlus.some((item: any) => node.data.id === item);
  } else {
    console.error('node or node.data or node.data.id is null or undefined');
  }

  //ncPassing
  // return props.noShowPlus.some((item: any) => {!node.data.id.include(item)});
  return true;
}

/**
 *
 * @param node
 */
let handleClick = (node: any) => {
  emit('scroll-to-section',node)
}

/**
 *
 * @param node
 */
let handlePlusClick = (event: MouseEvent, node: any) => {
  event.stopPropagation();  // 阻止事件冒泡
  emit('add-title', node);
};


/**
 * 移除节点
 */
let handleRemove = (event: MouseEvent, node: any) => {
  event.stopPropagation();  // 阻止事件冒泡
  console.log('tttttttt',node.data)
  if (node?.data?.children && node?.data?.children.length > 0) {
    ElMessage.error('存在子类，得一个个删')
    return
  }
  const parent = node.parent
  const children = parent?.data.children || parent?.data
  const index = children.findIndex((d:any) => d.id === node.data.id)
  children.splice(index, 1)
  emit('remove-title', node);
};


/**
 * 由子组件实现 父调用子
 */
defineExpose({resetChildTree ,addRootTitle,getChildNumber,getAllTree,initTree,data})

</script>

<style scoped lang="scss">

.node-show{
  position: relative;
  display: flex;
  width: 100%;
}


.el-tree {
  --el-fill-color-light: #8ce0e0;
  --el-color-primary-light-9: #8ce0e0;
  --el-tree-text-color: black;
}

.level-1 {
  font-size: 20px;
  font-weight: bold;
  color: black;
}

.level-2 {
  font-size: 18px;
}

.level-3 {
  font-size: 13px;
}

.level-4 {
  font-size: 12px;
}

</style>